﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web;

using MyData.DB.DBAccess.DBEntity;
using Common.Logging;
using Newtonsoft.Json;

namespace SH.STD.DataProvider
{
    public partial class DataAccess
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(DataAccess));

        private static readonly MSSQLHelper dbAccess = null;

        static DataAccess()
        {
            dbAccess = new MSSQLHelper(ConfigurationManager.ConnectionStrings["DB"].ConnectionString);
        }

        public static DataTable GetDataTable(string sql)
        {
            return dbAccess.ExecuteDataSet(CommandType.Text, sql).Tables[0];
        }

        public static string ConvertToJSON(DataTable dt, string dtName)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            using (JsonWriter jw = new JsonWriter(sw))
            {
                JsonSerializer ser = new JsonSerializer();
                jw.WriteStartObject();
                jw.WritePropertyName(dtName);
                jw.WriteStartArray();
                foreach (DataRow dr in dt.Rows)
                {
                    jw.WriteStartObject();

                    foreach (DataColumn dc in dt.Columns)
                    {
                        jw.WritePropertyName(dc.ColumnName);
                        ser.Serialize(jw, HttpUtility.UrlEncode(dr[dc].ToString()));
                    }

                    jw.WriteEndObject();
                }
                jw.WriteEndArray();
                jw.WriteEndObject();

                sw.Close();
                jw.Close();
            }

            return sb.ToString();
        }
    }
}
